#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
化学反应演算系统使用示例
演示如何查询化合物数据、设计化学反应、计算物料平衡和热力学分析
"""

from reaction_modeling_system import ReactionModelingSystem
import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def example_1_simple_combustion():
    """示例1: 简单燃烧反应 - 甲烷燃烧"""
    print("\n" + "="*80)
    print("示例1: 甲烷燃烧反应")
    print("="*80)
    
    # 创建系统实例
    system = ReactionModelingSystem(data_dir="data/example1")
    
    # 设计反应
    reaction = system.design_reaction(
        reaction_id="RXN-001",
        reaction_name="甲烷完全燃烧",
        equation="CH4 + 2O2 → CO2 + 2H2O",
        query_compounds=False,  # 不查询在线数据库（加快演示）
        thermodynamics={
            'delta_H': -890.3,  # kJ/mol
            'delta_G': -818.0,  # kJ/mol
            'delta_S': -242.8,  # J/(mol·K)
            'temperature': 298.15
        },
        reaction_type="完全燃烧",
        conditions={
            'temperature': 298.15,
            'pressure': 101.325,
            'phase': 'gas'
        }
    )
    
    # 计算物料平衡
    # 假设投入10 kg甲烷
    reactant_masses = {
        'CH4': 10.0,  # kg
        'O2': 40.0    # kg (过量)
    }
    
    # 生成工艺报告
    report = system.generate_process_report(
        reaction_id="RXN-001",
        reactant_masses=reactant_masses,
        yield_factor=0.95,  # 95%收率
        temperature=298.15
    )
    
    print(report)
    
    # 保存报告
    system.save_report(report, "data/example1/methane_combustion_report.txt")
    
    # 导出反应数据
    system.export_reactions("data/example1/reactions.json")


def example_2_synthesis_reaction():
    """示例2: 合成反应 - 氨合成（Haber-Bosch工艺）"""
    print("\n" + "="*80)
    print("示例2: 氨合成反应 (Haber-Bosch工艺)")
    print("="*80)
    
    system = ReactionModelingSystem(data_dir="data/example2")
    
    # 设计反应
    reaction = system.design_reaction(
        reaction_id="RXN-002",
        reaction_name="氨合成",
        equation="N2 + 3H2 → 2NH3",
        query_compounds=False,
        thermodynamics={
            'delta_H': -92.4,   # kJ/mol
            'delta_G': -33.0,   # kJ/mol
            'delta_S': -198.8,  # J/(mol·K)
            'temperature': 673.15  # 400°C
        },
        reaction_type="合成反应",
        catalyst="铁催化剂",
        conditions={
            'temperature': 673.15,  # 400°C
            'pressure': 20000,      # 200 atm
            'catalyst': 'Fe3O4/Al2O3/K2O'
        }
    )
    
    # 物料平衡计算
    reactant_masses = {
        'N2': 100.0,  # kg
        'H2': 30.0    # kg
    }
    
    # 生成报告
    report = system.generate_process_report(
        reaction_id="RXN-002",
        reactant_masses=reactant_masses,
        yield_factor=0.15,  # 单程转化率15%
        temperature=673.15
    )
    
    print(report)
    system.save_report(report, "data/example2/ammonia_synthesis_report.txt")
    system.export_reactions("data/example2/reactions.json")


def example_3_organic_synthesis():
    """示例3: 有机合成 - 酯化反应"""
    print("\n" + "="*80)
    print("示例3: 酯化反应 - 乙酸乙酯合成")
    print("="*80)
    
    system = ReactionModelingSystem(data_dir="data/example3")
    
    # 设计反应
    reaction = system.design_reaction(
        reaction_id="RXN-003",
        reaction_name="乙酸乙酯合成",
        equation="C2H4O2 + C2H6O → C4H8O2 + H2O",
        query_compounds=False,
        thermodynamics={
            'delta_H': -4.2,    # kJ/mol (微放热)
            'delta_G': 0.5,     # kJ/mol
            'delta_S': -15.8,   # J/(mol·K)
            'temperature': 351.15  # 78°C
        },
        reaction_type="酯化反应",
        catalyst="浓硫酸",
        conditions={
            'temperature': 351.15,  # 78°C
            'pressure': 101.325,
            'catalyst': 'H2SO4 (浓)',
            'reflux': True
        }
    )
    
    # 物料平衡
    reactant_masses = {
        'C2H4O2': 60.0,  # 乙酸 60 kg
        'C2H6O': 50.0    # 乙醇 50 kg
    }
    
    report = system.generate_process_report(
        reaction_id="RXN-003",
        reactant_masses=reactant_masses,
        yield_factor=0.65,  # 65%收率
        temperature=351.15
    )
    
    print(report)
    system.save_report(report, "data/example3/esterification_report.txt")
    system.export_reactions("data/example3/reactions.json")


def example_4_complex_process():
    """示例4: 复杂工艺 - 多步反应（苯酚降解）"""
    print("\n" + "="*80)
    print("示例4: 复杂工艺 - Fenton催化降解苯酚")
    print("="*80)
    
    system = ReactionModelingSystem(data_dir="data/example4")
    
    # 步骤1: Fenton反应生成羟基自由基
    rxn1 = system.design_reaction(
        reaction_id="RXN-004-1",
        reaction_name="Fenton反应",
        equation="Fe2+ + H2O2 → Fe3+ + OH- + OH",
        query_compounds=False,
        thermodynamics={
            'delta_H': -45.2,
            'delta_G': -38.5,
            'delta_S': -22.4,
            'temperature': 298.15
        },
        reaction_type="氧化还原",
        catalyst="Fe2+",
        conditions={
            'temperature': 298.15,
            'pH': 3.0,
            'H2O2_concentration': '30%'
        }
    )
    
    # 步骤2: 羟基自由基氧化苯酚
    rxn2 = system.design_reaction(
        reaction_id="RXN-004-2",
        reaction_name="苯酚氧化",
        equation="C6H6O + OH → C6H6O2",
        query_compounds=False,
        thermodynamics={
            'delta_H': -125.3,
            'delta_G': -98.7,
            'delta_S': -89.2,
            'temperature': 298.15
        },
        reaction_type="自由基氧化",
        conditions={
            'temperature': 298.15,
            'pH': 3.0
        }
    )
    
    # 步骤3: 进一步矿化
    rxn3 = system.design_reaction(
        reaction_id="RXN-004-3",
        reaction_name="完全矿化",
        equation="C6H6O2 + 14OH → 6CO2 + 10H2O",
        query_compounds=False,
        thermodynamics={
            'delta_H': -2850.0,
            'delta_G': -2650.0,
            'delta_S': -670.0,
            'temperature': 298.15
        },
        reaction_type="完全氧化",
        conditions={
            'temperature': 298.15,
            'pH': 3.0
        }
    )
    
    # 生成各步骤报告
    print("\n--- 步骤1: Fenton反应 ---")
    report1 = system.generate_process_report(
        reaction_id="RXN-004-1",
        reactant_masses={'Fe2+': 0.056, 'H2O2': 0.34},
        yield_factor=0.90,
        temperature=298.15
    )
    print(report1)
    
    print("\n--- 步骤2: 苯酚氧化 ---")
    report2 = system.generate_process_report(
        reaction_id="RXN-004-2",
        reactant_masses={'C6H6O': 0.094, 'OH': 0.017},
        yield_factor=0.85,
        temperature=298.15
    )
    print(report2)
    
    # 导出所有反应
    system.export_reactions("data/example4/phenol_degradation_reactions.json")
    
    # 保存综合报告
    combined_report = f"""
{'='*80}
复杂工艺综合报告: Fenton催化降解苯酚
{'='*80}

工艺概述:
本工艺采用Fenton催化氧化技术降解水中苯酚污染物，通过Fe2+催化H2O2
产生强氧化性的羟基自由基(·OH)，将苯酚逐步氧化降解至CO2和H2O。

工艺流程:
1. Fenton反应: Fe2+ + H2O2 → Fe3+ + OH- + ·OH
2. 苯酚氧化: C6H6O + ·OH → C6H6O2 (邻苯二酚)
3. 完全矿化: C6H6O2 + 14·OH → 6CO2 + 10H2O

关键参数:
- 反应温度: 25°C (298.15 K)
- pH值: 3.0
- H2O2浓度: 30%
- Fe2+投加量: 0.056 kg
- 苯酚初始浓度: 200 mg/L

预期效果:
- 苯酚降解率: >95%
- COD去除率: >90%
- 矿化率: >85%

{'='*80}

{report1}

{report2}

{'='*80}
综合报告生成完成
{'='*80}
"""
    
    system.save_report(combined_report, "data/example4/comprehensive_report.txt")


def example_5_query_pubchem():
    """示例5: 查询PubChem数据库（需要网络连接）"""
    print("\n" + "="*80)
    print("示例5: 从PubChem查询化合物数据")
    print("="*80)
    print("注意: 此示例需要网络连接，将从PubChem下载真实数据")
    print("="*80)
    
    system = ReactionModelingSystem(data_dir="data/example5")
    
    # 查询单个化合物
    print("\n查询化合物: 乙醇")
    ethanol = system.query_compound("ethanol", search_type="name")
    
    if ethanol:
        print(f"名称: {ethanol.name}")
        print(f"分子式: {ethanol.molecular_formula}")
        print(f"分子量: {ethanol.molecular_weight}")
        print(f"SMILES: {ethanol.smiles}")
        print(f"InChI: {ethanol.inchi}")
    
    # 批量查询
    print("\n批量查询化合物:")
    compounds = system.batch_query_compounds(
        ["water", "methanol", "acetone"],
        search_type="name"
    )
    
    for comp in compounds:
        print(f"  {comp.name}: {comp.molecular_formula} (MW: {comp.molecular_weight})")
    
    # 使用查询到的数据设计反应
    if len(compounds) >= 2:
        print("\n使用查询数据设计反应...")
        reaction = system.design_reaction(
            reaction_id="RXN-005",
            reaction_name="示例反应",
            equation="CH4O + O2 → CO2 + 2H2O",
            query_compounds=True,  # 自动查询
            thermodynamics={
                'delta_H': -726.0,
                'delta_G': -702.0,
                'delta_S': -80.5,
                'temperature': 298.15
            }
        )
        
        print(f"反应已创建: {reaction.reaction_name}")


def main():
    """主函数"""
    print("""
╔════════════════════════════════════════════════════════════════════════════╗
║                     化学反应演算建模系统                                    ║
║                  Chemical Reaction Modeling System                         ║
╚════════════════════════════════════════════════════════════════════════════╝

功能特性:
✓ 从PubChem等公共数据库查询化合物数据
✓ 自动解析化学反应方程式
✓ 计算物料平衡和理论产量
✓ 热力学分析（焓变、吉布斯自由能、平衡常数）
✓ 生成详细的工艺报告
✓ 支持多步复杂反应设计

""")
    
    # 运行示例
    try:
        example_1_simple_combustion()
        example_2_synthesis_reaction()
        example_3_organic_synthesis()
        example_4_complex_process()
        
        # 可选: 查询在线数据库（需要网络）
        # example_5_query_pubchem()
        
    except Exception as e:
        logger.error(f"运行示例时出错: {str(e)}", exc_info=True)
    
    print("""
╔════════════════════════════════════════════════════════════════════════════╗
║                          所有示例运行完成                                   ║
║                                                                            ║
║  生成的文件:                                                                ║
║    - data/example1/methane_combustion_report.txt                          ║
║    - data/example2/ammonia_synthesis_report.txt                           ║
║    - data/example3/esterification_report.txt                              ║
║    - data/example4/comprehensive_report.txt                               ║
║    - data/example*/reactions.json                                         ║
╚════════════════════════════════════════════════════════════════════════════╝
""")


if __name__ == "__main__":
    main()

